package com.sian.security.web.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import com.sian.security.utils.SHA1;
import com.sian.security.web.model.Credential;

//@Component
public class CredentialDaoImpl extends HibernateDaoSupport implements CredentialDao{

	@Autowired
	public void init(SessionFactory factory) {
	    setSessionFactory(factory);
	}
	
	@Override
	public void addCredential(Credential credential) {
		credential.setJ_password(SHA1.encode(credential.getJ_password()));
		getHibernateTemplate().save(credential);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Credential> findAllCredential() {
		return getHibernateTemplate().find("from credential");
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Credential> searchCredential(Credential credential) 
	{
		Session session = getSessionFactory().openSession();
		Query query = session.createQuery("from Credential as c where c.j_username = ? and c.j_password = password(:password) and c.enabled=true");
		query.setParameter(0, credential.getJ_username());
		query.setParameter("password", credential.getJ_username() + "/" + credential.getJ_password());
		//Query query = session.createFilter(credential, "from Credential");
		return query.list();
	}
}
